<template>
	<div class="main-body">
		<div class="allRole">
			<div>全部角色（{{ roleList.length }}）</div>
			<el-button size="mini" @click="addRole">新增角色</el-button>
		</div>
		<div v-for="item in roleList" :key="item.id" class="role" :class="roleId === item.id ? 'selectedRole' : ''" @click="showRole(item)">
			<span>{{ item.rName }}（{{ item.num }}）</span>
			<span class="edit-button">
				<el-dropdown>
					<i class="el-icon-more edit-button-Style" />
					<template #dropdown>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item @click.native="editRole(item)">编辑</el-dropdown-item>
							<el-dropdown-item v-if="item.num === 0" @click.native="delRoleApi(item)">删除</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
			</span>
		</div>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getRoleList, delRole, defaultAddRoleData } from '/@/api/role'

export default {
	name: 'roleManagement',
	components: {},
	props: {},
	setup(props, { emit }) {
		const state = reactive({
			roleId: '',
			roleList: []
		})

		// 向父组件抛出id
		const throwOut = (data, type) => {
			emit('input', data)
			emit('type', type)
		}

		const getRoleListApi = () => {
			getRoleList({}).then(res => {
				const { datas = [] } = res

				state.roleList = datas

				if (state.roleList.length > 0) {
					state.roleId = state.roleList[0].id

					// 抛出role
					throwOut(state.roleList[0], 3)
				}
			})
		}

		const addRole = () => {
			throwOut(defaultAddRoleData, 1)
		}

		const showRole = item => {
			state.roleId = item.id
			throwOut(item, 3)
		}

		const editRole = item => {
			state.roleId = item.id
			throwOut(item, 2)
		}

		const delRoleApi = item => {
			ElMessageBox.confirm('确定要删除该角色吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				delRole({ id: item.id })
					.then(() => {
						ElMessage.success('删除成功')
					})
					.finally(() => {
						getRoleListApi()
					})
			})
		}

		onMounted(() => {
			getRoleListApi()
		})

		return {
			addRole,
			showRole,
			editRole,
			delRoleApi,
			getRoleListApi,
			...toRefs(state)
		}
	}
}
</script>

<style lang="scss" scoped>
.main-body {
	background-color: #fff;
	height: 100%;
}
.allRole {
	padding: 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.role {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 1px;
	height: 36px;
	padding: 16px 20px;
	color: rgba(0, 0, 0, 0.85);
	font-size: 12px;
	cursor: pointer;
}
.selectedRole {
	background: #f0f6ff;
}

.edit-button {
	right: -5px;
	transform: rotate(90deg);
}

.edit-button-Style {
	color: #c6c6c6;
}
</style>
